package com.md.mainpage.presenter

import android.R.id
import android.content.ContentResolver
import android.content.Context
import android.util.Log
import com.md.basedpc.base.BasePresenter
import com.md.mainpage.R
import com.md.mainpage.interfaces.MainPageContract
import com.md.mainpage.model.MainPageModel
import com.md.mainpage.model.MainPageModelV2
import com.md.network.api.Category
import com.md.network.api.Group


const val TAG="MainPagePresenter"
class MainPagePresenter(var context: Context) : BasePresenter<MainPageContract.View>(), MainPageContract.Presenter {

    //首页面分类先用本地数据，后续新开接口了再接入
    private val localMainpageModel by lazy {
        MainPageModel()
    }
    private val mainpageModel by lazy {
        MainPageModelV2()
    }

    fun getLoacalCategoryList(){
        mRootView?.apply{
            setCateDetailList(localMainpageModel.getMainCategory())
        }
    }

    override fun getCateDetailList() {
        checkViewAttached()
        val disposable = mainpageModel.getCategoryDetailList()
                .subscribe({ categories ->
                    mRootView?.apply {
                        setCateDetailList(assembleCategory(categories))

                    }
                }, { throwable ->
                    mRootView?.apply {
                        showError(throwable.toString())

                    }
                })

        disposable?.let { addSubscription(it) }
    }

    fun assembleCategory(categories:ArrayList<Category>):ArrayList<Category>{
        var result = ArrayList<Category>()
        if(categories.size>6){
           var index = 0
            while (index<=6){
                result.add(categories[index++])
            }
        }else{
            result.addAll(categories)
        }
        var moreCategory = Category("","",ArrayList<Group>(),"",getResPath(R.drawable.main_more_category),"更多",false)
        result.add(moreCategory)
        return result
    }

    fun getResPath(id:Int):String{
        return (ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + context.resources.getResourcePackageName(id) + "/"
                + context.resources.getResourceTypeName(id) + "/"
                + context.resources.getResourceEntryName(id))
    }


    override fun getDailyAlbums() {
        checkViewAttached()
        val disposable = mainpageModel.getDailyAlbums()
                .subscribe({ albums ->
                    mRootView?.apply {
                        setDailyAlbums(albums)
                        Log.e(TAG,"categories.size=${albums.size}")
                    }
                }, { throwable ->
                    mRootView?.apply {
                        showError(throwable.toString())
                        Log.e(TAG,throwable.toString())
                    }
                })

        disposable?.let { addSubscription(it) }
    }


}